import base64
import random
import time

from PIL import Image, ExifTags
from django.conf import settings


# base43 to image
def base64_to_image(img, id):
    ines = img.split(';base64,')
    image_type = ines[0].split('/')[1]  # 获取图片格式
    image_data = base64.b64decode(ines[1])
    image_name = str(int(time.time())) + str(random.randrange(1000, 9999)) + str(id)

    file_path = 'media/mood/{0}.{1}'.format(image_name, image_type)  # 绝对路径

    save_img = open(file_path, 'wb')
    save_img.write(image_data)
    save_img.close()

    time.sleep(0.5)
    image = Image.open(file_path)
    width = image.width
    height = image.height
    rate = 1.0  # 压缩率
    # 根据图像大小设置压缩率
    if width >= 2000 or height >= 2000:
        rate = 0.3
    elif width >= 1000 or height >= 1000:
        rate = 0.5
    elif width >= 500 or height >= 500:
        rate = 0.9

    width = int(width * rate)  # 新的宽
    height = int(height * rate)  # 新的高

    # try:
    #     # 解决手机上传图片会旋转90度的问题
    #     for orientation in ExifTags.TAGS.keys():
    #         if ExifTags.TAGS[orientation] == 'Orientation':
    #             break
    #     exif = dict(image._getexif().items())
    #
    #     if exif[orientation] == 3:
    #         image = image.rotate(180, expand=True)
    #     elif exif[orientation] == 6:
    #         image = image.rotate(270, expand=True)
    #     elif exif[orientation] == 8:
    #         image = image.rotate(90, expand=True)
    #
    #     image.thumbnail((width, height), Image.ANTIALIAS)  # 生成缩略图
    #
    #     thumbnail_path = 'media/mood/{0}_thumbnail.{1}'.format(image_name, image_type)
    #
    #     # 相对路径,存放到数据库，到前端显示
    #     image.save(thumbnail_path)  # 保存到原路径
    #     time.sleep(1)
    #
    #     file_url = '{0}{1}/{2}.{3}'.format(settings.MEDIA_URL, 'mood', image_name, image_type)  # 相对路径
    #     thumbnail_url = '{0}{1}/{2}_thumbnail.{3}'.format(settings.MEDIA_URL, 'mood', image_name, image_type)
    #
    #     return thumbnail_url
    # except:
    #     pass

    image.thumbnail((width, height), Image.ANTIALIAS)  # 生成缩略图

    thumbnail_path = 'media/mood/{0}_thumbnail.{1}'.format(image_name, image_type)

    # 相对路径,存放到数据库，到前端显示
    image.save(thumbnail_path)  # 保存到原路径
    time.sleep(1)

    file_url = '{0}{1}/{2}.{3}'.format(settings.MEDIA_URL, 'mood', image_name, image_type)  # 相对路径
    thumbnail_url = '{0}{1}/{2}_thumbnail.{3}'.format(settings.MEDIA_URL, 'mood', image_name, image_type)

    return file_url, thumbnail_url
